<template>
  <div class="seal-top">
    <div class="btn-return">
      <el-page-header icon="ArrowLeft" content="发起签署任务" @back="$router.push('/wel/index')"/>
    </div>
    <div class="btn-group" >
        <el-button @click="saveSign(0)" type="info" plain>保存草稿</el-button>
        <el-button @click="saveSign(3)" type="info" >直接发起</el-button>
    </div>
  </div>
  <div class="basic-main">
    <el-form ref="signFormRef"
             :model="signForm"
             :rules="signFormRules">
      <div class="card-item">
        <!--------------------------------------------------【任务基本信息】-------------------------------------------------->
        <div class="card-bg">
          <div class="card-header"><div class="card-header_title"><span>任务基本信息</span></div></div>
          <div class="card-desc"></div>
          <div class="card-body" >
            <el-form-item label="任务主题" prop="signName">
              <el-input v-model="signForm.signName" placeholder="请输入任务主题" style="width: 500px;"/>
            </el-form-item>
          </div>
        </div>

        <!--------------------------------------------------【合同文件】-------------------------------------------------->
        <div class="card-bg">
          <div class="card-header">
            <div class="card-header_title"><span>合同文件</span></div>
            <div class="card-header_content">
              <span class="card-header-content">（请上传pdf格式的文件）</span>
            </div>
          </div>
          <div class="card-body">
            <div class="doc-wrapper new-doc-wrapper">
              <div class="DocUpload-wrap">
                <div class="DocUpload-body">
                  <el-upload
                      action
                      :limit="1"
                      :file-list="fileList"
                      :http-request="handleUpload"
                      :before-upload="beforeUpload"
                  >
                    <div class="upload-file-item" style="margin-right:25px">
                      <el-button type="primary"><el-icon><UploadFilled /></el-icon>添加签署文件</el-button>
                    </div>
                  </el-upload>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!--------------------------------------------------【任务参与人】-------------------------------------------------->
        <div class="card-bg">
          <div class="card-header">
            <div class="card-header_title"><span>任务参与人</span></div>
          </div>
          <div class="card-desc"></div>
          <div class="card-body">
            <div class="doc-wrapper new-doc-wrapper">
              <div>
                <el-table :data="signForm.sealSigner">
                  <el-table-column label="参与方" min-width="200">
                    <template #default="scope">
                      <el-input v-model="scope.row.signerRole"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="权限" min-width="100">
                    <template #default="scope">
                      签署
                    </template>
                  </el-table-column>
                  <el-table-column label="参与主体" min-width="100">
                    <template #default="scope">
                      个人
                    </template>
                  </el-table-column>
                  <el-table-column label="参与人" min-width="500">
                    <template #default="scope">
                      <el-autocomplete
                          style="width: 400px;"
                          v-model="scope.row.signerId"
                          :fetch-suggestions="querySearchAsync"
                          placeholder="请输入参与人姓名或者手机号"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="100">
                    <template #default="scope">
                      <el-button text size="small" @click.prevent="deleteRow(scope.$index)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <br/>
              <div class="DocUpload-wrap">
                <div class="DocUpload-body">
                  <div class="upload-file-item" >
                    <el-button type="primary" @click="addSigner"><el-icon><UploadFilled /></el-icon>添加参与方</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!--------------------------------------------------【其他设置】-------------------------------------------------->
        <div class="card-bg">
          <div class="card-header"><div class="card-header_title"><span>其他设置</span></div></div>
          <div class="card-desc"></div>
          <div class="card-body">
            <el-form
                ref="ruleFormRef"
                label-width="120px"
                class="demo-ruleForm"
            >
              <el-form-item label="签订截止日期：" prop="signDeadline">
                <el-date-picker
                    v-model="signForm.signDeadline"
                    type="datetime"
                    placeholder="请选择截止日期"
                />
                <span style="margin-left: 10px;font-size: 12px;color: #999;">如果流程在指定日期过后还没有签订完成，则本次签署自动过期，无法继续签订</span>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </el-form>

  </div>
</template>

<script setup>
import {ref,getCurrentInstance} from 'vue';
import {ElMessage} from 'element-plus';
import {validatenull} from '../../utils/validate';
import {getUserBySearchApi} from '../../api/user';
import {addSealSignApi, getSealSignBySignIdApi, getSealSignDraftApi, updateSignBasicApi} from '../../api/sign';
import {getParenthesesStr} from '../../utils/util';
import {useStore} from 'vuex';
import '../../css/Sign/seal_use.css'
const {proxy} = getCurrentInstance()

//接收传过来的路由信息
const signId = ref("")
signId.value = proxy.$route.query.signId

const fileList = ref([])

/**
 * 如果路由信息不为空
 */
const getSealSignBySignId = () =>{
  if(!validatenull(signId.value)){
    getSealSignDraftApi(signId.value)
        .then(res=>{
          let data = res.data.result
          signForm.value = data
          fileList.value.push({
            name: signForm.value.signFileName,
            url: signForm.value.signFilePath,
          })
          signForm.value.signParticipant = []
          signForm.value.sealSigner = []
        }).catch(res=>{
      ElMessage.error(res)
    })
  }
}
getSealSignBySignId()

const signFormRef = ref(null)
const signForm = ref({
  signName: '', //签署任务名称
  signFilePath: '', //签署文件路径
  signAttachFilePath: '', //任务附属文件路径
  signSponsor: '', //签署任务发起人
  signParticipant: [], //签署任务参与人
  signDeadline: '', //签署截止时间
  signStatus: 0, //任务状态
  signFileName: '',
  sealSigner: [{
    signerRole: '任务参与人1',
    signerId: '',
  }]
})

/**
 * 新增任务参与人
 */
const addSigner = () => {
  console.log(signForm.value.sealSigner)
  signForm.value.sealSigner.push({
    signerRole: '任务参与人',
    signerId: '',
  })
}

/**
 * 删除任务参与人
 * @param index
 */
const deleteRow = (index) => {
  signForm.value.sealSigner.splice(index, 1)
}

const signFormRules = ref({
  signName: [{required: true,message: "请输入签署任务名称", trigger: 'blur'}],
  signFilePath: [{required: true,message: "请上传签署文件", trigger: 'blur'}],
  signParticipant: [{required: true,message: "请输入任务参与人", trigger: 'blur'}],
  signDeadline: [{required: true,message: "请选择截止日期", trigger: 'blur'}],
})


/**
 * 根据用户输入实时获取数据库中的信息
 * @param queryString
 * @param callback
 */
const querySearchAsync = (queryString,callback) => {
  let list = [{}]
  if(!validatenull(queryString)){
    getUserBySearchApi(queryString).then(res=>{
      let data = res.data.result
      if(!validatenull(data)) {
        //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
        for (let i of data) {
          i.value = i.userName + "(" + i.userId + ")";  //将想要展示的数据作为value
        }
        list = data;
      }else {
        data.value = "该用户不存在"
        list.push(data)
      }
      callback(list);
    })
  }
}

/**
 * 上传文件前校验
 */
const beforeUpload = (file) => {
  if(file.type !== "application/pdf"){
    ElMessage.error("请上传pdf格式的文件！")
    return false
  }else if (file.size / 1024 / 1024 > 10) {
    ElMessage.error('上传文件大小不能超过10MB!')
    return false
  }
  return true
}
/**
 * 上传pdf至阿里云oss
 */
const handleUpload = (req) => {
  signForm.value.signFileName = req.file.name
  const keyName = req.file.uid+"."+req.file.name.split(".")[1];
  proxy.$OSS.put(keyName,req.file)
      .then(({res, url, name})=>{
        signForm.value.signFilePath = url
      })
      .catch(res=>{
        ElMessage.error(res)
      })
}

const store = useStore()

/**
 * 文件签署操作方法
 */
const saveSign = (status) => {
    signForm.value.signStatus = status
    signForm.value.signSponsor = store.getters.userId
  for (let i=0;i<signForm.value.sealSigner.length;i++){
    signForm.value.sealSigner[i].signerId = getParenthesesStr(signForm.value.sealSigner[i].signerId)
    signForm.value.signParticipant.push(signForm.value.sealSigner[i].signerId)
  }
    signForm.value.signParticipant = signForm.value.signParticipant.toString()
    if(!validatenull(signId.value))
    {
      if(status === 3){
        signFormRef.value.validate((valid,fields)=>{
          if(valid){
            console.log(signForm.value)
            updateSignBasicApi(signForm.value)
                .then(res=>{
                  let data = res.data.result
                  if(data === 'success'){
                    proxy.$router.push({
                      path:'/sign/seal-assign',
                      query:{
                        signId: signId.value
                      }
                    })
                  }else {
                    ElMessage.error("操作失败，请重试！")
                  }
                })
          }
        })
      }else {
        updateSignBasicApi(signForm.value)
            .then(res=>{
              let data = res.data.result
              if(data === 'success'){
                ElMessage.success("草稿保存成功！")
                proxy.$router.push("/wel/index")
              }else {
                ElMessage.error("操作失败，请重试！")
              }
            })
      }
    }else {
      if(status === 3) {
        signFormRef.value.validate((valid, fields) => {
          if (valid) {
            addSealSignApi(signForm.value)
                .then(res=>{
                  if(res.data.responseSuccess){
                      proxy.$router.push({
                        path:'/sign/seal-assign',
                        query:{
                          signId: res.data.result
                        }
                      })
                  }else {
                    ElMessage.error("保存错误，请重试！")
                  }
                }).catch(res=>{
              ElMessage.error(res)
            })
          }
        })
      }else {
        addSealSignApi(signForm.value)
            .then(res=>{
              if(res.data.responseSuccess){
                ElMessage.success("草稿保存成功！")
                proxy.$router.push("/wel/index")
              }else {
                ElMessage.error("保存错误，请重试！")
              }
            }).catch(res=>{
          ElMessage.error(res)
        })
      }
    }
}
</script>

<style scoped>

/* 表格样式 */
/deep/ .el-table{
  margin-top: 10px;
}
/deep/ .el-table th{
  border-bottom: 1px solid #e8eaec !important;
}
/deep/ .el-table__header-wrapper th{
  background: #f8f8f9;
  color: #515a6e;
}

.basic-main{
  margin-top: 30px;
  padding: 0 120px;
}
.card-item{
  margin-top: 70px;
  z-index: 0;
}
.card-item .card-bg{
  display: inline-block;
  width: 100%;
  margin-top: 12px;
  -webkit-box-shadow: 0 0 0 1px rgb(0 0 0 / 4%), 0 2px 4px 0 rgb(0 0 0 / 6%);
  box-shadow: 0 0 0 1px rgb(0 0 0 / 4%), 0 2px 4px 0 rgb(0 0 0 / 6%);
  border-radius: 3px;
  background-color: #fff;
  -webkit-transition: all .15s ease;
  transition: all .15s ease;
  overflow: hidden;
}
.card-bg:hover{
  box-shadow: 2px 4px 7px rgb(0,0,0,.15);
}
.card-header {
  position: relative;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  height: 48px;
  line-height: 48px;
  padding: 0 24px;
  padding-right: 200px;
}
.card-header .card-header_title{
  height: 48px;
  line-height: 48px;
  display: inline-block;
}
.card-header .card-header_title span{vertical-align:middle}
.card-header .card-header_content{
  margin-left: 10px;
}
.card-header .card-header_content .card-header-content{
  font-size: 12px;
  color: #999;
}
.card-desc{
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  margin-top: -4px;
}
.card-body{
  padding: 8px 24px 24px;
  overflow: hidden;
}
.card-body  .subtitle{
  height: 20px;
  line-height: 20px;
  font-size: 12px;
  color: #999;
}
.card-body .subTitle{
  line-height: 20px;
}
.subTitle .el-button{
  padding: 5px 0;
  font-size: 14px;
  font-weight: 400;
  color: #4d4d4d;
}
.el-button--text {
  border-color: transparent;
  color: #0975e1;
  background: 0 0;
  padding-left: 0;
  padding-right: 0;
}
.doc-wrapper {
  margin-top: 24px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: block;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}
.DocUpload-wrap{
  position: relative;
}
.DocUpload-body{
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}
.upload-file-item{
  border: 1px dashed #d9d9d9;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  height: 40px;
  text-align: center;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  cursor: pointer;
}
.upload-file-item:hover{background-color: #ecf5ff}
/deep/ .el-upload{
  width: 1240px;
}

/deep/ .upload-demo{
  display: flex;
  text-align: center;
  margin: 0 auto;
}
/deep/ .el-button--primary{
  background: none;
  color: #1063f1;
  border: none;
}
/deep/ .el-icon{
  padding-right: 5px;
  font-size: 20px;
}
/deep/ .el-input__inner{
  margin-left: 4px;
}
.basic-btn{
  position: fixed;
  top: 110px;
  width: 100%;
  padding: 5px 0;
  background-color: #f0f2f5;
  z-index: 10;
}
/deep/ .el-button--info{
  width: 120px;
  margin: 0 10px;
  color: #fff;
  background-color: #1063f1;
  border-color: #1063f1;
  font-size: 15px;
}
/deep/ .el-button--info:hover{
  background-color: #0082FF;
  border-color: #0082FF;
}

/deep/ .el-button--info.is-plain{
  width: 120px;
  margin: 0 10px;
  color: #1063f1;
  background-color:#ecf5ff;
  border-color: #ecf5ff;
  font-size: 15px;
}
/deep/ .el-button--info.is-plain:hover{
  background-color:#1063f1;
  border-color:#1063f1;
  color: #fff;
}
</style>
